package vip.denglei.company.controller.app;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyV3Response;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyV3Result;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderV3Request;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderV3Result;
import com.github.binarywang.wxpay.bean.result.enums.TradeTypeEnum;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.google.gson.Gson;
import com.kuaidi100.sdk.response.SubscribeResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import vip.denglei.company.mapper.WorkWechatMsgContextMapper;
import vip.denglei.company.mapper.WorkWechatMsgInfoMapper;
import vip.denglei.company.model.app.AppUserInfo;
import vip.denglei.company.model.app.AppUserOrder;
import vip.denglei.company.model.app.AppUserOrderDetails;
import vip.denglei.company.model.app.bo.AppUserOrderBO;
import vip.denglei.company.model.app.bo.BindingLogisticsBO;
import vip.denglei.company.model.app.query.AppUserOrderQuery;
import vip.denglei.company.service.app.AppUserOrderDetailsService;
import vip.denglei.company.service.app.AppUserOrderService;
import vip.denglei.company.service.app.AppUserService;
import vip.denglei.company.util.HttpResult;
import vip.denglei.company.util.WorkWechatSendMsgUtils;
import vip.denglei.company.util.kuidi100.SubscribePushParamResp;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * (app_user_order)表控制层
 *
 * @author xxxxx
 */
@RestController
@RequestMapping("/appUserOrder")
@Slf4j
public class AppUserOrderController {
    /**
     * 服务对象
     */
    @Resource
    private AppUserOrderService appUserOrderService;
    @Resource
    private AppUserService appUserService;

    @Resource
    private WxPayService wxPayService;
    @Autowired
    public WorkWechatMsgContextMapper workWechatMsgContextMapper;
    @Autowired
    public WorkWechatMsgInfoMapper workWechatMsgInfoMapper;

    @Resource
    public AppUserOrderDetailsService applicationUserOrderDetailsService;

    /**
     * 提交订单
     *
     * @param appUserOrderBO
     * @return
     */
    @PostMapping("save/userOrder")
    public HttpResult saveUserOrder(@RequestBody AppUserOrderBO appUserOrderBO, HttpServletRequest request) {
        log.info("AppUserOrderController saveUserOrder 参数 appUserOrderBO:{}", appUserOrderBO);
        return appUserOrderService.saveUserOrder(appUserOrderBO);
    }

    /**
     * 取消订单
     *
     * @param orderId
     * @param request
     * @return
     */
    @PutMapping("cancel/userOrder/{orderId}")
    public HttpResult cancelUserOrderByOrderId(@PathVariable String orderId, HttpServletRequest request) {
        log.info("AppUserOrderController cancelUserOrderByOrderId 参数 orderId:{}", orderId);
        LambdaQueryWrapper<AppUserOrder> appUserOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        appUserOrderLambdaQueryWrapper.eq(AppUserOrder::getOrderId, orderId);
        AppUserOrder appUserOrder = appUserOrderService.getOne(appUserOrderLambdaQueryWrapper);
        //未支付才可以取消
        if (Objects.nonNull(appUserOrder) && appUserOrder.getOrderStatus() == 0) {
            appUserOrder.setOrderStatus(4);
            appUserOrderService.updateById(appUserOrder);
        }
        return HttpResult.success();
    }

    /**
     * 催发货
     *
     * @param orderId
     * @param request
     * @return
     */
    @PutMapping("urgeShipment/userOrder/{orderId}")
    public HttpResult urgeShipmentOrderByOrderId(@PathVariable String orderId, HttpServletRequest request) {
        log.info("AppUserOrderController urgeShipmentOrderByOrderId 参数 orderId:{}", orderId);

        return HttpResult.success();
    }


    /**
     * @param orderId
     * @param request
     * @return
     */
    @GetMapping("query/userOrderDetails/{orderId}")
    public HttpResult queryUserOrderDetailsByOrderId(@PathVariable String orderId, HttpServletRequest request) {
        log.info("AppUserOrderController queryUserOrderDetailsByOrderId 参数 orderId:{}", orderId);
        return appUserOrderService.queryUserOrderDetailsByOrderId(orderId);
    }

    /**
     * 微信预下单
     *
     * @param appUserOrder
     * @param request
     * @return
     */

    @PostMapping("query/getOrderPayInfo")
    public HttpResult getOrderPayInfo(@RequestBody AppUserOrder appUserOrder, HttpServletRequest request) {
        log.info("AppUserOrderController getOrderPayInfo 参数 appUserOrderBO:{}", appUserOrder);

        WxPayUnifiedOrderV3Result.JsapiResult wxPayMpOrderResult = null;
        WxPayUnifiedOrderV3Request wxPayUnifiedOrderV3Request = null;
        if (Objects.nonNull(appUserOrder)) {
            LambdaQueryWrapper<AppUserOrder> appUserOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
            appUserOrderLambdaQueryWrapper.eq(AppUserOrder::getOrderId, appUserOrder.getOrderId());
            AppUserOrder queryOrder = appUserOrderService.getOne(appUserOrderLambdaQueryWrapper);
            if (Objects.nonNull(queryOrder)) {
                if (queryOrder.getPaymentStatus().equals(1)) {
                    return HttpResult.err("该订单已经支付，请勿重复支付");
                }
                queryOrder.setOutTradeNo("wx" + IdUtil.getSnowflakeNextId());
                appUserOrderService.updateById(queryOrder);
                LambdaQueryWrapper<AppUserInfo> appUserInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                appUserInfoLambdaQueryWrapper.eq(AppUserInfo::getUserId, appUserOrder.getUserId());
                AppUserInfo appUserInfo = appUserService.getOne(appUserInfoLambdaQueryWrapper);
                if (Objects.nonNull(appUserInfo)) {
                    wxPayUnifiedOrderV3Request = new WxPayUnifiedOrderV3Request();
                    //调起支付的人的 openId
                    WxPayUnifiedOrderV3Request.Payer payer = new WxPayUnifiedOrderV3Request.Payer();
                    payer.setOpenid(appUserInfo.getWechatId());
                    wxPayUnifiedOrderV3Request.setPayer(payer);
                    //订单编号
                    wxPayUnifiedOrderV3Request.setOutTradeNo(queryOrder.getOutTradeNo());
                    //订单金额
                    wxPayUnifiedOrderV3Request.setAmount(new WxPayUnifiedOrderV3Request.Amount().setTotal(queryOrder.getProTotal()));
                    //商品描述
                    wxPayUnifiedOrderV3Request.setDescription("description");
                    //回调的 URL 地址
                    wxPayUnifiedOrderV3Request.setNotifyUrl("https://hbcaiyu.cn/company/appUserOrder/weChatPayNotify");
                    try {
                        wxPayMpOrderResult = wxPayService.createOrderV3(TradeTypeEnum.JSAPI, wxPayUnifiedOrderV3Request);
                    } catch (WxPayException e) {
                        throw new RuntimeException(e);
                    }
                    log.info("微信调用返回wxPayUnifiedOrderResult{}:", wxPayMpOrderResult);

                }

            }
        }

        return HttpResult.success(wxPayMpOrderResult);
    }

    @PostMapping(value = "/weChatPayNotify")
    public String weChatPayNotify(@RequestBody String notifyData, HttpServletRequest request) {
        log.info("AppUserOrderController weChatPayNotify 参数 notifyData:{}", notifyData);

        try {
            WxPayNotifyV3Result wxPayNotifyV3Result = wxPayService.parseOrderNotifyV3Result(notifyData, null);
            log.info("支付结果回调解析 参数 wxPayNotifyV3Result:{}", wxPayNotifyV3Result);
            LambdaQueryWrapper<AppUserOrder> appUserOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
            appUserOrderLambdaQueryWrapper.eq(AppUserOrder::getOutTradeNo, wxPayNotifyV3Result.getResult().getOutTradeNo());
            AppUserOrder appUserOrder = appUserOrderService.getOne(appUserOrderLambdaQueryWrapper);
            if (Objects.nonNull(appUserOrder)) {
                appUserOrder.setPaymentStatus(1);
                appUserOrder.setOrderStatus(1);
                appUserOrder.setPaymentTime(DateUtil.date());
                appUserOrderService.updateById(appUserOrder);
                appUserOrderService.modifyInventory(appUserOrder.getOrderId());
                //发货通知
                if (appUserOrder.getPushStatus().equals(0)) {
                    LambdaQueryWrapper<AppUserOrderDetails> appUserOrderDetailsLambdaQueryWrappera = new LambdaQueryWrapper();
                    appUserOrderDetailsLambdaQueryWrappera.eq(AppUserOrderDetails::getOrderId, appUserOrder.getOrderId());
                    List<AppUserOrderDetails> appUserOrderDetailsList = applicationUserOrderDetailsService.list(appUserOrderDetailsLambdaQueryWrappera);
                    String concatenatedDetails = appUserOrderDetailsList.stream()
                            .map(orderDetails -> {
                                return "  #### 商品名称：" + orderDetails.getProName() + " ,数量：`" + orderDetails.getProVolume() + orderDetails.getProUnit() + "`,单价：`" + orderDetails.getProPrice() / 100 + "`元\\n";
                            })
                            .collect(Collectors.joining(""));
                    WorkWechatSendMsgUtils.setBotMsg("# 新订单通知\\n订单编号：" + appUserOrder.getOrderId() + "\\n订单总金额：`" + appUserOrder.getProTotal() / 100 + "`元\\n订单时间：" + DateUtil.formatDateTime(appUserOrder.getCreateTime()) + "\\n" +
                            "## 发货地址信息 \\n#### 收货人名称：" + appUserOrder.getAddName() + ",\\n #### 收货人电话：" + appUserOrder.getAddPhone() + ",\\n#### 收货人地址：" +
                            appUserOrder.getProvince() + appUserOrder.getCity() + appUserOrder.getCounty() + appUserOrder.getAddInfo() + appUserOrder.getCompanyName() +
                            "\\n> ## 发货商品信息\\n>" +
                            concatenatedDetails +
                            "`请注意发货`", "markdown", 1, 5, workWechatMsgInfoMapper, workWechatMsgContextMapper);
                    log.info("完成订单群推送 参数 wxPayNotifyV3Result:{}", appUserOrder.getOrderId());
                    appUserOrder.setPushStatus(1);
                    appUserOrderService.updateById(appUserOrder);
                }
                return WxPayNotifyV3Response.success("200");
            }
        } catch (WxPayException e) {
            throw new RuntimeException(e);
        }
        return WxPayNotifyV3Response.fail("微信支付回调成功");
    }

    /**
     * 用户查询订单列表
     *
     * @param appUserOrderQuery
     * @return
     */
    @PostMapping("query/userOrderPage")
    public HttpResult queryUserOrderPage(@RequestBody AppUserOrderQuery appUserOrderQuery) {
        log.info("AppUserOrderController queryUserOrderPage 参数 appUserOrderQuery:{}", appUserOrderQuery);
        return appUserOrderService.queryUserOrderPage(appUserOrderQuery);
    }

    /**
     * 用户查询订单列表
     *
     * @param bindingLogistics
     * @return
     */
    @PostMapping("bindingLogistics")
    public HttpResult bindingLogistics(@RequestBody BindingLogisticsBO bindingLogistics) {
        log.info("AppUserOrderController bindingLogistics 参数 bindingLogistics:{}", bindingLogistics);
        return appUserOrderService.bindingLogistics(bindingLogistics);
    }


    @PostMapping(value = "/logisticsNotify")
    public SubscribeResp logisticsNotify(HttpServletRequest request) {
        log.info("AppUserOrderController logisticsNotify 参数 request:{}", request);
        // 获取参数
        String param = request.getParameter("param");
        log.info("AppUserOrderController logisticsNotify 参数 param:{}", param);
        return appUserOrderService.LogisticsNotify(new Gson().fromJson(param, SubscribePushParamResp.class));
    }


}
